from faker import Faker
import random
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from data_mock.utils import FileUtil, MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 医嘱相关基础数据 ==========
ORDER_TYPES = ['长期医嘱', '临时医嘱']
ORDER_CLASSES = ['药品医嘱', '治疗医嘱', '检查医嘱']
ORDER_ITEMS = [
    # 癌症相关药物（化疗、靶向药）
    ("顺铂注射液", "针剂", "100mg", "静脉注射", "化疗"),
    ("紫杉醇注射液", "针剂", "30mg", "静脉点滴", "化疗"),
    ("培美曲塞二钠", "针剂", "500mg", "静脉点滴", "化疗"),
    ("贝伐珠单抗", "针剂", "100mg", "静脉注射", "靶向"),
    ("伊马替尼片", "片剂", "0.1g", "口服", "靶向"),
    # 放疗、支持治疗
    ("放疗医嘱", "治疗", "1次", "直线加速器", "放疗"),
    ("止吐药-昂丹司琼", "片剂", "8mg", "口服", "支持"),
    ("止痛药-吗啡片", "片剂", "10mg", "口服", "支持")
]
FREQUENCIES = [("qd", "每日一次"), ("bid", "每日两次"), ("tid", "每日三次"), ("qod", "隔日一次")]
INJECTION_TYPES = ['静脉注射', '肌肉注射', '皮下注射']
DEPARTMENTS = ['肿瘤科', '放疗科', '化疗中心', '内科', '外科']


# ========== 时间范围配置 ==========
def generate_DAY_RANGE(start_day, end_day):
    start = datetime.strptime(start_day, "%Y-%m-%d")
    end = datetime.strptime(end_day, "%Y-%m-%d")
    days = []
    current = start
    while current <= end:
        days.append(current.strftime("%Y-%m-%d"))
        current += relativedelta(days=1)
    return days


DAY_RANGE = generate_DAY_RANGE("2025-08-01", "2025-08-03")


def generate_records_per_day(day: str):
    date_obj = datetime.strptime(day, '%Y-%m-%d')
    return 10 if date_obj.day % 2 == 0 else 5


# ========== 核心生成函数 ==========
def generate_order_records():
    sql_statements = []
    record_count = 0

    patient_id_counter = 2001
    visit_sn_counter = 2001
    order_sn_counter = 30001

    for day in DAY_RANGE:
        RECORDS_PER_day = generate_records_per_day(day)
        for i in range(1, RECORDS_PER_day + 1):
            record_count += 1
            patient_id = f"PT{patient_id_counter}"
            patient_id_counter += 1

            visit_sn = f"VIS{visit_sn_counter}"
            visit_sn_counter += 1

            medical_record_no = f"MR{random.randint(100000, 999999)}"
            inpatient_no = f"IP{random.randint(100000, 999999)}"
            order_sn = f"ORD{order_sn_counter}"
            order_sn_counter += 1

            request_no = f"REQ{random.randint(10000, 99999)}"
            order_given_time = fake.date_time_between(
                start_date=datetime.strptime(day, "%Y-%m-%d"),
                end_date=(datetime.strptime(day, "%Y-%m-%d") + timedelta(days=1))
            ).strftime('%Y-%m-%d %H:%M:%S')

            order_dept_name = random.choice(DEPARTMENTS)
            order_doctor_no = f"DOC{random.randint(100, 999)}"
            visit_dept_name = random.choice(DEPARTMENTS)

            order_start_datetime = order_given_time
            order_end_datetime = (datetime.strptime(order_start_datetime, "%Y-%m-%d %H:%M:%S") +
                                  timedelta(days=random.randint(1, 5))).strftime('%Y-%m-%d %H:%M:%S')

            executive_dept_name = random.choice(DEPARTMENTS)
            order_type = random.choice(ORDER_TYPES)
            order_class_name = random.choice(ORDER_CLASSES)

            # 选一个癌症相关的药物/治疗
            order_item = random.choice(ORDER_ITEMS)
            order_item_name, form, spec, administration_route, category = order_item

            order_group_no = f"GRP{random.randint(1000, 9999)}"
            dose = str(random.randint(1, 2))
            dose_unit = spec
            frequency_code, frequency_name = random.choice(FREQUENCIES)
            injection_type = administration_route if administration_route in INJECTION_TYPES else None

            num_of_order = str(random.randint(1, 10))
            num_of_order_unit = "盒" if form == "片剂" else "支"

            order_note = f"{category}相关医嘱"
            drug_flag = "是" if form in ["片剂", "针剂"] else "否"
            manufac = fake.company()
            trade_name = f"{order_item_name}商品名"
            order_status = random.choice(["执行中", "已停止", "已完成"])

            record_status = random.randint(0, 1)
            yy_batch_time = day
            yy_record_batch_id = f"BATCH{day}_{i}"
            yy_etl_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'medical_record_no': medical_record_no,
                'inpatient_no': inpatient_no,
                'order_sn': order_sn,
                'request_no': request_no,
                'order_given_time': order_given_time,
                'order_dept_name': order_dept_name,
                'order_doctor_no': order_doctor_no,
                'visit_dept_name': visit_dept_name,
                'order_start_datetime': order_start_datetime,
                'order_end_datetime': order_end_datetime,
                'executive_dept_name': executive_dept_name,
                'order_type': order_type,
                'order_class_name': order_class_name,
                'order_item_name': order_item_name,
                'order_group_no': order_group_no,
                'dose': dose,
                'dose_unit': dose_unit,
                'form': form,
                'spec': spec,
                'frequency_code': frequency_code,
                'frequency_name': frequency_name,
                'administration_route': administration_route,
                'injection_type': injection_type,
                'num_of_order': num_of_order,
                'num_of_order_unit': num_of_order_unit,
                'order_note': order_note,
                'drug_flag': drug_flag,
                'manufac': manufac,
                'trade_name': trade_name,
                'order_status': order_status,
                'record_status': record_status,
                'yy_etl_time': yy_etl_time,
                'yy_upload_status': 0,
                'yy_upload_time': None,
                'yy_batch_time': yy_batch_time,
                'yy_record_batch_id': yy_record_batch_id,
                'yy_backfill_time': None,
                'yy_backfill_status': None
            }

            sql = _generate_sql('b10_1', data)
            sql_statements.append(sql)

    return sql_statements


def _generate_sql(table, data):
    columns = ', '.join([f'`{k}`' for k in data.keys()])
    values = []
    for v in data.values():
        if v is None:
            values.append('NULL')
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({columns}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    records = generate_order_records()
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b10_1')
    # 或写入 SQL 文件
    # FileUtil.generate_sql_file(records, "b10_1_order_records.sql")
